import { getClassList, register } from '../../api/clazz'
import { generateToken } from '../../api/user'
import { toast } from '../../utils/extendApi'
import { clearStorage } from '../../utils/storage';
Page({
  data: {
    userName: '',
    password: '',
    nickName: '',
    classesIndex: 1,
    classesIds: [],
    classesArray: [],
    sex: '2',
    status: '0'
  },
  onUsernameInput(e) {
    this.setData({
      userName: e.detail.value
    });
  },
  onPasswordInput(e) {
    this.setData({
      password: e.detail.value
    });
  },
  onNickNameInput(e) {
    this.setData({
      nickName: e.detail.value
    });
  },
  radioChange: function (e) {
    this.setData({
      sex: e.detail.value
    });
  },
  bindClassesChange: function (e) {
    this.setData({
      classesIndex: e.detail.value
    });
  },
  onLoad: function () {
    // 将临时token和timestamp存储到本地
    generateToken();
    // 获取班级列表
    getClassList((res) => {
      if (res != null) {
        // 处理班级列表数据,前2个数据为内蒙古大学、计算机学院、不需要展示
        const classesArray = res.data.slice(2).map(item => '内蒙古大学计算机学院' + item.classesName);
        const classesIds = res.data.slice(2).map(item => + item.classesId);
        this.setData({
          classesArray: classesArray,
          classesIds: classesIds
        });
      }
    });
  },
  confirmRegister() {
    const { userName, password, nickName, sex, status } = this.data;
    if (!userName || !password || !nickName) {
      toast({
        title: '学号、密码和姓名不能为空',
        icon: 'none'
      });
      return;
    }
    const classesId = this.data.classesIds[this.data.classesIndex]
    // 调用注册接口
    register(userName, password, nickName, classesId, sex, status)
    // 清理临时变量
    clearStorage()
  }
})